package com.project;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.DriverManager;

@Configuration
@ComponentScan(basePackageClasses = MybatisConfig.class)
@EnableTransactionManagement
@MapperScan("com.project.mapper")
public class MybatisConfig {

    @Bean
    public DataSource getDataSource(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:6789/spring?characterEncoding=utf-8&allowMultiQueries=true");
        source.setUsername("root");
        source.setPassword("lovo");

        source.setMaxActive(100);
        source.setMinIdle(20);
        source.setMaxWait(1000);

        return source;
    }

    @Bean
    public SqlSessionFactoryBean getSqlsessionFactory(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(this.getDataSource());
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));
        return factoryBean;
    }

    @Bean
    public TransactionManager getTransactionManager(){
        DataSourceTransactionManager trans = new DataSourceTransactionManager(getDataSource());
        return trans;
    }
}
